package com.ryan.security.async;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * Created by kaimin on 1/1/2019.
 * time : 14:39
 */
@Component  //系统开启好了之后的监听器
@Slf4j
public class QueueLisner implements ApplicationListener<ContextRefreshedEvent>{


    @Autowired
    private MockQueue mockQueue;


    @Autowired
    private DeferredResultHolder holder;


    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {


        new Thread(()->{
            while (true) {
                if (StringUtils.isNotBlank(mockQueue.getCompleteOrder())) {

                    String order = mockQueue.getCompleteOrder();
                    log.info("返回订单处理结果："+order);
                    holder.getMap().get(order).setResult("订单处理成功");
                    mockQueue.setCompleteOrder(null);//不会循环处理
                } else {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        //由于这个是在祝线程中，所以，需要另开线程，不然会阻塞主线程
        /*while (true) {
            if (StringUtils.isNotBlank(mockQueue.getCompleteOrder())) {

                String order = mockQueue.getCompleteOrder();
                log.info("返回订单处理结果："+order);
                holder.getMap().get(order).setResult("订单处理成功");
                mockQueue.setCompleteOrder(null);//不会循环处理
            } else {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }*/
    }
}
